package com.atguigu.order.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.atguigu.order.bean.Order;
import com.atguigu.order.properties.OrderProperties;
import com.atguigu.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/api/order")
@Slf4j
@RestController
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderProperties orderProperties;
//    @Value("${order.timeout}")
//    String orderTimeout;
//    @Value("${order.auto-confirm}")
//    String orderAutoConfirm;
    @GetMapping("/config")
    public String config() {
        return "order.timeout:" + orderProperties.getTimeout()
                + "order.auto-confirm:" + orderProperties.getAutoConfirm()
                + "order.db-url:" + orderProperties.getDbUrl();
    }

    //创建订单
    @GetMapping("/create")
    public Order creatOrder(@RequestParam("productId") Long productId,
                            @RequestParam("userId") Long userId) {
        return orderService.createOrder(productId, userId);
    }
    @GetMapping("/seckill")
    @SentinelResource(value = "seckill-order",blockHandler = "seckillFallback")
    public Order seckill(@RequestParam("productId") Long productId,
                            @RequestParam("userId") Long userId) {
        Order order = orderService.createOrder(productId, userId);
        order.setId(Long.MAX_VALUE);
        return order;
    }
    public Order seckillFallback(Long productId, Long userId,BlockException e) {
        System.out.println("seckillFallback兜底回调");
        Order order = new Order();
        order.setId(productId);
        order.setUserId(userId);
        order.setAddress("异常信息"+e.getClass());
        return order;
    }
    @GetMapping("/writeDb")
    public String writeDb(){
        return "writeDb";
    }
    @GetMapping("/readDb")
    public String readDb(){
        log.info("readDb");
        return "readDb";
    }
}
